package com.mtt.thirdapi.oujian.util;

import com.alibaba.fastjson.JSONObject;
import com.mtt.thirdapi.oujian.config.OjConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * @Description: java类作用描述
 * @Author: guomengzhou
 * @CreateDate: 2019/8/13$ 13:41$
 * @UpdateUser: guomengzhou
 * @UpdateDate: 2019/8/13$ 13:41$
 * @Version: 1.0
 */
@Slf4j
public class OJApiUtils {
    /**
     * 向指定路径发送post请求（json传值）
     * @param url
     * @param requestData
     * @return
     * @throws Exception
     */
    public static String httpPostWithJSON(String url, String requestData) throws Exception {

        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        String respContent = null;

        // json方式
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("apiName", OjConfig.apiName);
        jsonParam.put("apiToken", OjConfig.apiToken);
        if(null != requestData){
            JSONObject requestJson = JSONObject.parseObject(requestData);
            jsonParam.putAll(requestJson);
        }

        StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");//解决中文乱码问题
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        System.out.println();


        // 表单方式
        //List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
        //pairList.add(new BasicNameValuePair("name", "admin"));
       // pairList.add(new BasicNameValuePair("pass", "123456"));
        //httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));


        HttpResponse resp = client.execute(httpPost);
        if (resp.getStatusLine().getStatusCode() == 200) {
            HttpEntity he = resp.getEntity();
            respContent = EntityUtils.toString(he, "UTF-8");
        }
        return respContent;
    }
}
